package com.beone.admin.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * token相关工具
 * </p>
 *
 * @author Pagenny
 * @date 2019-05-19 12:13
 **/
@Component
public class TokenUtils {

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 超时时间（秒）
     */
    @Value("${token.timeout.second}")
    private int TIMEOUT_SECOND = 1800;

    private static final String TOKEN_PREFIX = "user:token:";

    /** 参数token */
    private static final String PARAM_TOKEN = "token";

    /**
     * 从请求的header或参数中获取token
     * @param request
     * @return
     */
    public String getTokenFromReq(HttpServletRequest request) {
        String token = request.getHeader(PARAM_TOKEN);
        return StringUtils.isEmpty(token) ? request.getParameter(PARAM_TOKEN) : token;
    }

    /**
     * 通过token获取用户id
     *
     * @param token
     * @return
     */
    public String getUserId(String token) {
        return redisUtils.getRedisStringValue(TOKEN_PREFIX + token);
    }

    /**
     * 设置用户token至缓存
     *
     * @param userId
     * @param token
     * @return
     */
    public void setUserToken(String userId, String token) {
        redisUtils.setRedisStringValue(TOKEN_PREFIX + token, userId, TIMEOUT_SECOND);
    }

    public void removeToken(String token) {
        redisUtils.deleteRedisObject(TOKEN_PREFIX + token);
    }
}
